package com.yxh.service.impl;

import com.github.pagehelper.PageInfo;
import com.yxh.common.Constants;
import com.yxh.pojo.*;
import com.yxh.pojo.tree.BaseTreeGrid;
import com.yxh.pojo.vo.UserVO;
import com.yxh.service.*;
import com.yxh.util.TreeUtil;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import java.util.UUID;

/**
 * Created by 32988 on 2018/5/30.
 */
@Component
public class TokenManagerImpl implements TokenManager {

    @Autowired
    private RedisClient redis;

    @Autowired
    private GroupService groupService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private DeptService deptService;

    public TokenModel createToken(String userId) {
        String token = UUID.randomUUID().toString().replace("-", "");
        TokenModel model = new TokenModel(userId, token);
        redis.set(Constants.CURRENT_USER_ID + model.getUserId(), token);
        redis.expire(Constants.CURRENT_USER_ID + model.getUserId(), 60 * 30);
        return model;
    }

    public TokenModel getToken(String authentication) {
        if (authentication == null || authentication.length() == 0) {
            return null;
        }
        String[] param = authentication.split("_");
        if (param.length != 2) {
            return null;
        }
        String userId = param[0];
        String token = param[1].replace("web","");
        return new TokenModel(userId, token);
    }


    public boolean checkToken(TokenModel model) {
        if (model == null) {
            return false;
        }
        String token = redis.get(Constants.CURRENT_USER_ID + model.getUserId());
        if (token == null || !token.equals(model.getToken())) {
            return false;
        }
        redis.expire(Constants.CURRENT_USER_ID + model.getUserId(), 60 * 30);
        return true;
    }


    public UserVO AssemblingData(User user) {
        Menu m = new Menu();
        PageInfo<Menu> pageInfoMenus = menuService.getInformation(m, 1, 1000);
        List<Menu> menus = pageInfoMenus.getList();

        Dept dept = new Dept();
        dept.setDeptId(user.getDept());
        PageInfo<Dept> pageInfoDepts = deptService.getInformation(dept, 1, 1000);
        List<Dept> depts = pageInfoDepts.getList();

        TreeUtil tree = new TreeUtil();
        List<BaseTreeGrid> treeGrid = tree.transListTree(menus);
        String[] roles = user.getRole().split(",");
        for (String roleId : roles) {
            List<GroupMenu> listGroupMenu = groupService.selectByGroupId(roleId);
            for (GroupMenu groupMenu : listGroupMenu) {
                for (BaseTreeGrid baseTreeGrid : treeGrid) {
                    if (baseTreeGrid.getId().equals(groupMenu.getMenuId())) {
                        baseTreeGrid.setRoles(1);
                    }
                    if(!CollectionUtils.isEmpty(baseTreeGrid.getChildren())){
                        for (BaseTreeGrid baseTreeGridCrildrens : baseTreeGrid.getChildren()) {
                            if (baseTreeGridCrildrens.getId().equals(groupMenu.getMenuId())) {
                                baseTreeGridCrildrens.setRoles(1);
                            }
                        }
                    }

                }
            }
        }
        UserVO userVO = new UserVO();
        try {
            BeanUtilsBean.getInstance().copyProperties(userVO, user);
            userVO.setMenu(treeGrid);
            if(depts!=null){
                userVO.setDeptName(depts.get(0).getDeptName());
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return userVO;
    }


    public void deleteToken(String userId) {
        redis.del(Constants.CURRENT_USER_ID + userId);
    }
}
